package com.iemes.util;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
/**
 * 导出Excel文档工具类
 * @date 2014-8-6
 * */
public class ExcelUtil {
	private static String excelPath = "/uploadFile/"+ new SimpleDateFormat("yyyyMMddHH").format(new Date()) + "";// 配置excel文档路径
    /**
     * 创建excel文档，
     * @param list 数据
     * @param keys list中map的key数组集合
     * @param columnNames excel的列名
     * */
    public static Workbook createWorkBook(List<Map<String, Object>> listMap,List<?> list) {
            // 创建excel工作簿
            Workbook wb = new HSSFWorkbook();
            // 创建第一个sheet（页），并命名
            Sheet sheet = wb.createSheet("数据");
            // 手动设置列宽。第一个参数表示要为第几列设；，第二个参数表示列的宽度，n为列高的像素数。
           /* for(int i=0;i<keys.length;i++){
                sheet.setColumnWidth((short) i, (short) (35.7 * 150));
            }*/

            // 创建第一行
            Row row = sheet.createRow((short) 0);

            // 创建两种单元格格式
            CellStyle cs = wb.createCellStyle();
            CellStyle cs2 = wb.createCellStyle();

            // 创建两种字体
            Font f = wb.createFont();
            Font f2 = wb.createFont();

            // 创建第一种字体样式（用于列名）
            f.setFontHeightInPoints((short) 10);
            f.setColor(IndexedColors.BLACK.getIndex());
            f.setBoldweight(Font.BOLDWEIGHT_BOLD);

            // 创建第二种字体样式（用于值）
            f2.setFontHeightInPoints((short) 10);
            f2.setColor(IndexedColors.BLACK.getIndex());

//            Font f3=wb.createFont();
//            f3.setFontHeightInPoints((short) 10);
//            f3.setColor(IndexedColors.RED.getIndex());

            // 设置第一种单元格的样式（用于列名）
            cs.setFont(f);
            cs.setBorderLeft(CellStyle.BORDER_THIN);
            cs.setBorderRight(CellStyle.BORDER_THIN);
            cs.setBorderTop(CellStyle.BORDER_THIN);
            cs.setBorderBottom(CellStyle.BORDER_THIN);
            cs.setAlignment(CellStyle.ALIGN_CENTER);

            // 设置第二种单元格的样式（用于值）
            cs2.setFont(f2);
            cs2.setBorderLeft(CellStyle.BORDER_THIN);
            cs2.setBorderRight(CellStyle.BORDER_THIN);
            cs2.setBorderTop(CellStyle.BORDER_THIN);
            cs2.setBorderBottom(CellStyle.BORDER_THIN);
            cs2.setAlignment(CellStyle.ALIGN_CENTER);
            for(int i=0;i<listMap.size();i++){
            	if(Boolean.parseBoolean(listMap.get(i).get("hide")+"")){
            		listMap.remove(listMap.get(i));
            	}
            }
            //设置列名
            for(int i=0;i<listMap.size();i++){
                Cell cell = row.createCell(i);
                cell.setCellValue(listMap.get(i).get("name")+"");
                cell.setCellStyle(cs);
            }
            //设置每行每列的值
            for (int i = 0; i < list.size(); i++) {
                // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
                // 创建一行，在页sheet上
                Row row1 = sheet.createRow(i+1);
                // 在row行上创建一个方格

                for(int j=0;j<listMap.size();j++){
                    Cell cell = row1.createCell(j);
                    Map<String, Object> map =(Map<String, Object>) list.get(i);
                    cell.setCellValue(map.get(listMap.get(j).get("colkey")) == null?" ": map.get(listMap.get(j).get("colkey")).toString());
                    cell.setCellStyle(cs2);
                }
            }
            return wb;    		

    }
    /**
     * 只是上传没有导入
     * @param attachs
     * @param request
     */
	public static void uploadExcel(MultipartFile attachs,HttpServletRequest request) {
		String getExcelPath = request.getServletContext().getRealPath(excelPath);
		File excel = new File(getExcelPath);
		if (!excel.exists())
		{
			excel.mkdir();
		}
		String originalFilename = attachs.getOriginalFilename();
		int lastDotIndex = originalFilename.lastIndexOf(".");
		// 后缀名
		String ext = originalFilename.substring(lastDotIndex + 1);
		String fileNewName = Common.generateFileName(originalFilename);
			try {	
				attachs.transferTo(new File(getExcelPath+"/"+fileNewName));
			} catch (Exception e) {
				e.printStackTrace();
		}

	}
	/**
	 * 写入excel文档
	 * @param rs
	 * @param headers
	 * @throws Exception
	 */
	public static void fillExcelData(HttpServletRequest request, HttpServletResponse response, ResultSet rs,String[] headers,String fileName)throws Exception{
		Workbook wb = new HSSFWorkbook();
		int rowIndex=0;
		Sheet sheet=wb.createSheet();
		Row row=sheet.createRow(rowIndex++);
		for(int i=0;i<headers.length;i++){
			row.createCell(i).setCellValue(headers[i]);
		}
		while(rs.next()){
			row=sheet.createRow(rowIndex++);
			for(int i=0;i<headers.length;i++){
				if (rs.getObject(i+1)!=null) {
					row.createCell(i).setCellValue(rs.getObject(i+1).toString());	
				}
			}
		}
		//导出文件
		export(request,response, wb, fileName);
	}
	
	/**
     * 导出Excel
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){

        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        if(wb == null){
            wb = new HSSFWorkbook();
        }

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }
   
    
    /**
     * 取文档数据
     * @param hssfCell
     * @return
     */
    public static String formatCell(HSSFCell hssfCell){
		if(hssfCell==null){
			return "";
		}else{
			if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
				return String.valueOf(hssfCell.getBooleanCellValue());
			}else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
				short format = hssfCell.getCellStyle().getDataFormat(); 
				   SimpleDateFormat sdf = null;  
				    if(format == 14 || format == 31 || format == 57 || format == 58){  
				        //日期  
				        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				        double value = hssfCell.getNumericCellValue();  
					    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);  
					    return sdf.format(date);
				    }else if (format == 20 || format == 32) {  
				        //时间  
				        sdf = new SimpleDateFormat("HH:mm:ss");  
				        double value = hssfCell.getNumericCellValue();  
					    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);  
					    return sdf.format(date);
				    }  
				   
				return String.valueOf(hssfCell.getNumericCellValue());
			}else{
				return String.valueOf(hssfCell.getStringCellValue());
			}
		}
	}
    
    
    /**
     * 导出文件
     * @param response
     * @param wb
     * @param fileName
     * @throws Exception
     */
    public static void export(HttpServletRequest request,HttpServletResponse response,Workbook wb,String fileName)throws Exception{
		response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
		ServletOutputStream out=response.getOutputStream();
		String getexcelPath = request.getServletContext().getRealPath(excelPath);
		System.out.println("上传的地址是哪里："+getexcelPath);
		File excel = new File(getexcelPath);
		if (!excel.exists())
		{
			excel.mkdir();
		}
		FileOutputStream os = new FileOutputStream(getexcelPath+fileName);
		wb.write(os);
		os.flush();
		os.close();
		
	}
    
    /**
     * 拿到Connection
     * @return
     */
    public static Connection getConnection(){
    	WebApplicationContext webApplicationContext = ContextLoader
				.getCurrentWebApplicationContext();
		SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) webApplicationContext
				.getBean("sqlSessionFactory");
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Connection conn = sqlSession.getConnection();
		return conn;
    }

}
